﻿// BusinessLicenseController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
using SimpleWebApi.Business.Service.Interface.DTO.BusinessLicenseDTO;
using SimpleWebApi.Business.Service.Interface.IBusinessLicense;
using SimpleWebApi.MyMigration.Models.BusinessLicenseManagement;

namespace BusinessLicenseApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class BusinessLicensesController : ControllerBase
    {
        private readonly IBusinessLicenseService _service;

        public BusinessLicensesController(IBusinessLicenseService service)
        {
            _service = service;
        }

        [HttpPost]
        [ProducesResponseType(typeof(BusinessLicense), 201)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> CreateBusinessLicense([FromBody] BusinessLicenseCreateDto dto)
        {

            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            try
            {
                var license = await _service.CreateBusinessLicenseAsync(dto);

                // 返回简化后的响应模型 (避免循环)
                //return CreatedAtAction(nameof(GetLicense), new { id = license.Id },
                //    new
                //    {
                //        license.Id,
                //        license.CreditCode,
                //        LegalPersonName = license.LegalPerson?.Name
                //    });
                return Ok(license);
            }
            catch (DbUpdateException ex) when (IsUniqueConstraintViolation(ex))
            {
                throw new InvalidOperationException("身份证号已存在", ex);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }
                
        [HttpPut]
        public async Task<IActionResult> UpdateBusinessLicense(
            [FromBody] BusinessLicenseUpdateDto dto)
        {
            var result = await _service.UpdateBusinessLicenseAsync(dto);
            return Ok(result);
        }

        
        [HttpGet("search")]
        public async Task<IActionResult> SearchLicenses([FromQuery] BusinessLicenseQueryDto queryDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _service.SearchLicensesAsync(queryDto);
            return Ok(result);
        }

        private bool IsUniqueConstraintViolation(DbUpdateException ex)
        {
            return ex.InnerException is MySqlException mysqlEx &&
                   mysqlEx.ErrorCode == MySqlErrorCode.DuplicateKeyEntry;
        }



        // 在 Controller 中调用
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(BusinessLicense), 200)]
        [ProducesResponseType(404)]
        public async Task<IActionResult> GetLicense(int id)
        {
            try
            {
                var license = await _service.GetLicenseByIdAsync(id);
                return license != null ? Ok(license) : NotFound();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}